{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "73b3ec970f104441b2cde8f9dbd04459",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "interactive(children=(Dropdown(description='model_name', options=('xception_coco_voctrainaug', 'xception_coco_…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "###  COPY ALL THE CODE INTO A JYPYTER NOTEBOOK  ### \n",
    "###  THE JYPYTER NOTEBOOK NEEDS TO BE IN 'tensorflow\\models\\research\\deeplab'  ### \n",
    "\n",
    "## Imports\n",
    "\n",
    "import collections\n",
    "import os\n",
    "import io\n",
    "import sys\n",
    "import tarfile\n",
    "import tempfile\n",
    "import urllib\n",
    "\n",
    "from IPython import display\n",
    "from ipywidgets import interact\n",
    "from ipywidgets import interactive\n",
    "from matplotlib import gridspec\n",
    "from matplotlib import pyplot as plt\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "import cv2\n",
    "# import skvideo.io\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "# Needed to show segmentation colormap labels\n",
    "sys.path.append('utils')\n",
    "import get_dataset_colormap\n",
    "\n",
    "\n",
    "## Select and download models\n",
    "\n",
    "\n",
    "_MODEL_URLS = {\n",
    "    'xception_coco_voctrainaug': 'http://download.tensorflow.org/models/deeplabv3_pascal_train_aug_2018_01_04.tar.gz',\n",
    "    'xception_coco_voctrainval': 'http://download.tensorflow.org/models/deeplabv3_pascal_trainval_2018_01_04.tar.gz',\n",
    "}\n",
    "\n",
    "Config = collections.namedtuple('Config', 'model_url, model_dir')\n",
    "\n",
    "def get_config(model_name, model_dir):\n",
    "    return Config(_MODEL_URLS[model_name], model_dir)\n",
    "\n",
    "config_widget = interactive(get_config, model_name=_MODEL_URLS.keys(), model_dir='')\n",
    "display.display(config_widget)\n",
    "\n",
    "# Check configuration and download the model\n",
    "\n",
    "# _TARBALL_NAME = 'deeplabv3_pascal_train_aug_2018_01_04.tar.gz'\n",
    "_TARBALL_NAME = 'deeplab_model.tar.gz'\n",
    "config = config_widget.result\n",
    "model_dir = 'C:\\\\Users\\\\whu801\\\\Desktop\\\\temp for deeplab'\n",
    "tf.gfile.MakeDirs(model_dir)\n",
    "\n",
    "download_path = os.path.join(model_dir, _TARBALL_NAME)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Load model in TensorFlow\n",
    "\n",
    "_FROZEN_GRAPH_NAME = 'frozen_inference_graph'\n",
    "\n",
    "\n",
    "class DeepLabModel(object):\n",
    "    \"\"\"Class to load deeplab model and run inference.\"\"\"\n",
    "    \n",
    "    INPUT_TENSOR_NAME = 'ImageTensor:0'\n",
    "    OUTPUT_TENSOR_NAME = 'SemanticPredictions:0'\n",
    "    INPUT_SIZE = 513\n",
    "\n",
    "    def __init__(self, tarball_path):\n",
    "        \"\"\"Creates and loads pretrained deeplab model.\"\"\"\n",
    "        self.graph = tf.Graph()\n",
    "        \n",
    "        graph_def = None\n",
    "        # Extract frozen graph from tar archive.\n",
    "        tar_file = tarfile.open(tarball_path)\n",
    "        for tar_info in tar_file.getmembers():\n",
    "            if _FROZEN_GRAPH_NAME in os.path.basename(tar_info.name):\n",
    "                file_handle = tar_file.extractfile(tar_info)\n",
    "                graph_def = tf.GraphDef.FromString(file_handle.read())\n",
    "                break\n",
    "\n",
    "        tar_file.close()\n",
    "        \n",
    "        if graph_def is None:\n",
    "            raise RuntimeError('Cannot find inference graph in tar archive.')\n",
    "\n",
    "        with self.graph.as_default():      \n",
    "            tf.import_graph_def(graph_def, name='')\n",
    "        \n",
    "        self.sess = tf.Session(graph=self.graph)\n",
    "            \n",
    "    def run(self, image):\n",
    "        \"\"\"Runs inference on a single image.\n",
    "        \n",
    "        Args:\n",
    "            image: A PIL.Image object, raw input image.\n",
    "            \n",
    "        Returns:\n",
    "            resized_image: RGB image resized from original input image.\n",
    "            seg_map: Segmentation map of `resized_image`.\n",
    "        \"\"\"\n",
    "        width, height = image.size\n",
    "        resize_ratio = 1.0 * self.INPUT_SIZE / max(width, height)\n",
    "        target_size = (int(resize_ratio * width), int(resize_ratio * height))\n",
    "        resized_image = image.convert('RGB').resize(target_size, Image.ANTIALIAS)\n",
    "        batch_seg_map = self.sess.run(\n",
    "            self.OUTPUT_TENSOR_NAME,\n",
    "            feed_dict={self.INPUT_TENSOR_NAME: [np.asarray(resized_image)]})\n",
    "        seg_map = batch_seg_map[0]\n",
    "        return resized_image, seg_map\n",
    "\n",
    "model = DeepLabModel(download_path)\n",
    "\n",
    "\n",
    "## Webcam demo\n",
    "\n",
    "cap = cv2.VideoCapture(0)\n",
    "\n",
    "# Next line may need adjusting depending on webcam resolution\n",
    "final = np.zeros((1, 384, 1026, 3))\n",
    "while True:\n",
    "    ret, frame = cap.read()\n",
    "    \n",
    "    # From cv2 to PIL\n",
    "    cv2_im = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n",
    "    pil_im = Image.fromarray(cv2_im)\n",
    "    \n",
    "    # Run model\n",
    "    resized_im, seg_map = model.run(pil_im)\n",
    "    \n",
    "    # Adjust color of mask\n",
    "    seg_image = get_dataset_colormap.label_to_color_image(\n",
    "        seg_map, get_dataset_colormap.get_pascal_name()).astype(np.uint8)\n",
    "    \n",
    "    # Convert PIL image back to cv2 and resize\n",
    "    frame = np.array(pil_im)\n",
    "    r = seg_image.shape[1] / frame.shape[1]\n",
    "    dim = (int(frame.shape[0] * r), seg_image.shape[1])[::-1]\n",
    "    resized = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)\n",
    "    masked_map = np.array(seg_image, copy=True)\n",
    "    for i in range(int(frame.shape[0] * r)):\n",
    "        for j in range(seg_image.shape[1]):\n",
    "            \n",
    "            if seg_map[i][j] == 5:\n",
    "                for k in range(3):\n",
    "                    masked_map[i][j][k] = resized[i][j][k]\n",
    "            else:\n",
    "                masked_map[i][j][0] = 0\n",
    "    resized = cv2.cvtColor(resized, cv2.COLOR_RGB2BGR)\n",
    "    masked_image = cv2.cvtColor(masked_map, cv2.COLOR_RGB2BGR)\n",
    "    \n",
    "    # Stack horizontally color frame and mask\n",
    "    color_and_mask = np.hstack((resized, seg_image, masked_image))\n",
    "\n",
    "    cv2.imshow('frame', color_and_mask)\n",
    "    if cv2.waitKey(25) & 0xFF == ord('q'):\n",
    "        cap.release()\n",
    "        cv2.destroyAllWindows()\n",
    "        break\n",
    "\n",
    "    \n",
    "###  UNCOMMENT NEXT LINES TO SAVE THE VIDEO  ###\n",
    "#    output = np.expand_dims(both, axis=0)\n",
    "#    final = np.append(final, output, 0)\n",
    "#skvideo.io.vwrite(\"outputvideo111.mp4\", final)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
